//
//  RepairView.m
//  GoldOperationClient
//
//  Created by yaxue wang on 16/9/21.
//  Copyright © 2016年 展鸿科技. All rights reserved.
//

#import "RepairView.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <Photos/Photos.h>
#import "TZImageManager.h"
#import "MapViewController.h"
#import "TZImagePickerController.h"
#import "D3RecordButton.h"
#import "TZVideoPlayerController.h"
#import "MWPhotoBrowser.h"
#import "GTMBase64.h"
#import"AFNetworking.h"
#include <CommonCrypto/CommonCrypto.h>
#import "QNUploadManager.h"
#import "UIImage+ResizeMagick.h"
#import"AFNetworkActivityIndicatorManager.h"
#import "TPKeyboardAvoidingScrollView.h"
#import <Photos/Photos.h>
#import "MWPhotoBrowser.h"
#import "KZVideoViewController.h"
#import "VoiceConverter.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <Photos/Photos.h>
@interface RepairView()<TZImagePickerControllerDelegate,UIImagePickerControllerDelegate,UIActionSheetDelegate,UIAlertViewDelegate,D3RecordDelegate,UIImagePickerControllerDelegate,UINavigationBarDelegate,MWPhotoBrowserDelegate,KZVideoViewControllerDelegate,UINavigationControllerDelegate>
{
    KZVideoModel *_videoModel;
    //图片
    NSMutableArray *_selectedAssets;
    NSMutableArray *_dataAr;
    NSMutableArray *_photoNumAr;
    NSMutableArray *_videoNumAr;
    NSMutableArray *_NumAr;
    NSString *_cityName;
    BOOL _isSelectOriginalPhoto;
     NSMutableArray *_soundAr;
    NSInteger _soundClick;
     NSString *_videoPath;
}
@property (nonatomic, strong) UIImagePickerController *imagePickerVc;

@end
@implementation RepairView
-(instancetype)initWithFrame:(CGRect)frame {

    self = [super initWithFrame:frame];
   if (self) {
       _dataAr =[[NSMutableArray alloc]init];
       _photoNumAr =[[NSMutableArray alloc]init];
       _videoNumAr =[[NSMutableArray alloc]init];
       _selectedAssets =[[NSMutableArray alloc]init];
       _NumAr =[[NSMutableArray alloc]init];
       _soundAr =[[NSMutableArray alloc]init];
       self.backgroundColor=[UIColor whiteColor];
       if (self.takePhone) {
           [self phone];
       }
       if (self.takeImage) {
           [self pushImagePickerController];
       }

       if (self.takeViedo) {
           [self getViedo];
       }


       
    }
 return self;
}
- (void)showData:(NSMutableArray*)dataAr
{
    CGFloat width =(WindowWidth-60-50)/3;
    //    if (_centerView == nil) {
    //        _centerView =[[UIView alloc]init];
    //        [_scrollView addSubview:_centerView];
    //    }
    //
    //    if (dataAr.count==4){
    //
    //        _centerView.frame=CGRectMake(0, CGRectGetMaxY(_headView.frame), WindowWidth-50, (width+60)*2);
    //
    //    }else  if (dataAr.count==0){
    //
    //        _centerView.frame=CGRectMake(0, CGRectGetMaxY(_headView.frame), WindowWidth-50, 0);
    //    }else
    //    {
    //        _centerView.frame=CGRectMake(0, CGRectGetMaxY(_headView.frame), WindowWidth-50, (width+60));
    //
    //    }
    //    _centerView.backgroundColor =[UIColor whiteColor];
    //
    //    for (UIView *view in [_centerView subviews]) {
    //        [view removeFromSuperview];
    //    }
    //    [_NumAr removeAllObjects];
    //
    for (int i=0; i<dataAr.count; i++) {
        
        NSDictionary *dic =[dataAr objectAtIndex:i];
        //只有图片
        UIImageView *img =[[UIImageView alloc]initWithFrame:CGRectMake(15+(width+15)*(i%3), 25+(width+60)*(i/3), width, width)];
        img.userInteractionEnabled=YES;
        img.image =[dic objectForKey:@"img"];;
        [self addSubview:img];
        img.userInteractionEnabled=YES;
        img.tag=100+i;
        if ([[dic objectForKey:@"type"]integerValue]==1) {
            [_NumAr addObject:[MWPhoto photoWithImage:[dic objectForKey:@"img"]]];
            
        }
        
        UIButton*deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        deleteBtn.frame =CGRectMake((width+15)*(i%3)+15, CGRectGetMaxY(img.frame), width, 35);
        [deleteBtn setTitle:@"删除"  forState:UIControlStateNormal];
        [deleteBtn setTitleColor:[UIColor colorWithRed:245/255.0 green:172/255.0 blue:84/255.0 alpha:1] forState:UIControlStateNormal];
        deleteBtn.tag=i;
        [deleteBtn addTarget:self action:@selector(deleteBtnClik:) forControlEvents:UIControlEventTouchUpInside];
        deleteBtn.titleLabel.font =F(14);
        [self addSubview:deleteBtn];
        
        UIImage *image =[UIImage imageNamed:@"Ico_home_play"];
        if ([[dic objectForKey:@"type"]integerValue]==2) {
            
            NSURL *url=[NSURL fileURLWithPath: _videoModel.videoAbsolutePath];
            [_NumAr addObject:[MWPhoto videoWithURL:url]];
            UIImageView* videoImageView = [[UIImageView alloc] initWithFrame:CGRectMake((img.frame.size.width-image.size.width)/2, (img.frame.size.height-image.size.height)/2, image.size.width, image.size.height)];
            videoImageView.contentMode = UIViewContentModeScaleAspectFill;
            videoImageView.image=image;
            [img addSubview:videoImageView];
        }
        [img bk_whenTapped:^{
            
            //            //预览图片
            MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
            // Present
            if (self.pushBrowser) {
                self.pushBrowser(browser);
                
            }
            //            [self.navigationController pushViewController:browser animated:YES];
            
            browser.displayActionButton = NO;
            browser.displayNavArrows = NO;
            browser.displaySelectionButtons = NO;
            browser.zoomPhotosToFill = YES;
            browser.alwaysShowControls = NO;
            browser.enableGrid = YES;
            browser.startOnGrid = NO;
            browser.autoPlayOnAppear = NO;
            [browser setCurrentPhotoIndex:i];
            
            
        }];
        
        
    }
    
}
#pragma mark - 拍照
- (void)phone
{
    if (_photoNumAr.count>2) {
        
        [CClass showMessage:@"最多上传3张图片"];
        return;
    }
    
#define push @#clang diagnostic pop
    // 调用相机
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
    {
        self.imagePickerVc.sourceType = sourceType;
        if(iOS8Later) {
            _imagePickerVc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        }
        if (self.pushImagePickerVc) {
            self.pushImagePickerVc(_imagePickerVc);
            
        }
        //               [self presentViewController:_imagePickerVc animated:YES completion:nil];
    } else {
        NSLog(@"模拟器中无法打开照相机,请在真机中使用");
    }

}



//拍照的时候调用  一旦选择了照片，ImagePicker 将回调 didFinishPickingMediaWithInfo
- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    if ([type isEqualToString:@"public.image"]) {
        
        TZImagePickerController *tzImagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:3 delegate:self];
        //        [tzImagePickerVc showProgressHUD];
        
        UIImage *image =  [CClass resizeImage:[info objectForKey:@"UIImagePickerControllerOriginalImage"] ByWidth:WindowWidth*2];
        
        
        // save photo and get asset / 保存图片，获取到asset
        [[TZImageManager manager] savePhotoWithImage:image completion:^{
            
            [[TZImageManager manager] getCameraRollAlbum:NO allowPickingImage:YES completion:^(TZAlbumModel *model) {
                [[TZImageManager manager] getAssetsFromFetchResult:model.result allowPickingVideo:NO allowPickingImage:YES completion:^(NSArray<TZAssetModel *> *models) {
                    
                    TZAssetModel *assetModel = [models firstObject];
                    if (tzImagePickerVc.sortAscendingByModificationDate) {
                        assetModel = [models lastObject];
                    }
                    
                    [_selectedAssets addObject:assetModel.asset];
                    NSDictionary *dict=[NSDictionary dictionaryWithObjectsAndKeys:@1,@"type",image,@"img", nil];
                    //总数
                    [_dataAr addObject:dict];
                    //图片数
                    [_photoNumAr addObject:dict];
                    //挑出来视频放在最后一位
                    for (int i=0; i<_dataAr.count; i++)
                    {
                        NSDictionary *dic =[_dataAr objectAtIndex:i];
                        NSInteger num =[[dic objectForKey:@"type"]integerValue];
                        
                        if (num==2){
                            NSDictionary *videoDict= [_dataAr objectAtIndex:i];
                            
                            [_dataAr removeObjectAtIndex:i];
                            [_dataAr insertObject:videoDict atIndex:[_dataAr count]];
                        }
                    }
                    [self showData:_dataAr];
                    
                }];
            }];
        }];
    }
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    if ([picker isKindOfClass:[UIImagePickerController class]]) {
        [picker dismissViewControllerAnimated:YES completion:nil];
    }
}
#pragma mark 删除
- (void)deleteBtnClik:(UIButton *)sender {
    
    NSDictionary *dic =[_dataAr objectAtIndex:sender.tag];
    
    if ([[dic objectForKey:@"type"]integerValue]==2)
    {
        [_videoNumAr removeAllObjects];
        
    }else
    {
        [_photoNumAr removeLastObject];
        //没有区分图片和视频
        [_selectedAssets removeObjectAtIndex:sender.tag];
    }
    
    [_dataAr removeObjectAtIndex:sender.tag];
    [self showData:_dataAr];
    
    
    
}
- (UIImagePickerController *)imagePickerVc {
    if (_imagePickerVc == nil) {
        _imagePickerVc = [[UIImagePickerController alloc] init];
        _imagePickerVc.delegate = self;
        // set appearance / 改变相册选择页的导航栏外观
//        _imagePickerVc.navigationBar.barTintColor = self.navigationController.navigationBar.barTintColor;
//        _imagePickerVc.navigationBar.tintColor = self.navigationController.navigationBar.tintColor;
        UIBarButtonItem *tzBarItem, *BarItem;
        if (iOS9Later) {
            tzBarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[TZImagePickerController class]]];
            BarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UIImagePickerController class]]];
        } else {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
            tzBarItem = [UIBarButtonItem appearanceWhenContainedIn:[TZImagePickerController class], nil];
            BarItem = [UIBarButtonItem appearanceWhenContainedIn:[UIImagePickerController class], nil];
#pragma clang diagnostic pop
        }
        NSDictionary *titleTextAttributes = [tzBarItem titleTextAttributesForState:UIControlStateNormal];
        [BarItem setTitleTextAttributes:titleTextAttributes forState:UIControlStateNormal];
    }
    return _imagePickerVc;
}
#pragma mark - 相册
- (void)pushImagePickerController {
    
    
    if (_photoNumAr.count>2) {
        
        [CClass showMessage:@"最多上传3张图片"];
        return;
    }
    
         TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:3 delegate:self];
#pragma mark - 四类个性化设置，这些参数都可以不传，此时会走默认设置
            imagePickerVc.isSelectOriginalPhoto = _isSelectOriginalPhoto;
            // 1.如果你需要将拍照按钮放在外面，不要传这个参数
            imagePickerVc.selectedAssets = _selectedAssets;
            imagePickerVc.allowTakePicture = NO; // 在内部显示拍照按钮
            // 3. 设置是否可以选择视频/图片/原图
            imagePickerVc.allowPickingVideo = NO;
            imagePickerVc.allowPickingImage =YES;
            imagePickerVc.allowPickingOriginalPhoto = YES;
            // 4. 照片排列按修改时间升序
            imagePickerVc.sortAscendingByModificationDate = YES;
#pragma mark - 到这里为
            // You can get the photos by block, the same as by delegate.
            // 你可以通过block或者代理，来得到用户选择的照片.
            [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
                
            }];
            if (self.pushVc) {
                self.pushVc(imagePickerVc);
                
            }
           
//            [self presentViewController:imagePickerVc animated:YES completion:nil];
    
        
   
    
}
#pragma mark - UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) { // 去设置界面，开启相机访问权限
        if (iOS8Later) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        } else {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=Privacy&path=Photos"]];
        }
    }
}
#pragma mark - TZImagePickerControllerDelegate

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto {
    _selectedAssets = [NSMutableArray arrayWithArray:assets];
    _isSelectOriginalPhoto = isSelectOriginalPhoto;
    
    //删除相册里面的和图片
    [_photoNumAr removeAllObjects];
    
    //删除相册和照相里面的，留下视频 总数据中
    
    for (int i=0; i<_dataAr.count; i++)
    {
        NSDictionary *dic =[_dataAr objectAtIndex:i];
        NSInteger num =[[dic objectForKey:@"type"]integerValue];
        
        if (num==1){
            
            [_dataAr removeObjectAtIndex:i];
            i--;
        }
        
        
    }
    if (_dataAr.count==0) {
        for (int i=0; i<photos.count; i++) {
            
            NSDictionary *dict=[NSDictionary dictionaryWithObjectsAndKeys:@1,@"type",[photos objectAtIndex:i],@"img", nil];
            
            [_dataAr addObject:dict];
            [_photoNumAr addObject:dict];
        }
        
    }else
    {
        NSDictionary *vodDic =[_dataAr lastObject];
        [_dataAr removeAllObjects];
        for (int i=0; i<photos.count; i++) {
            
            NSDictionary *dict=[NSDictionary dictionaryWithObjectsAndKeys:@1,@"type",[photos objectAtIndex:i],@"img", nil];
            
            [_dataAr addObject:dict];
            [_photoNumAr addObject:dict];
        }
        [_dataAr addObject:vodDic];
        
    }
    
    
    
    //相册相片的个数
    [self showData:_dataAr];
    
}

#pragma mark 录制视频
- (void)getViedo
{
    if (_videoNumAr.count>0) {
        
        [CClass showMessage:@"最多上传1段视频"];
        return;
    }            //授权成功，执行后续操作
    KZVideoViewController *videoVC = [[KZVideoViewController alloc] init];
    videoVC.delegate = self;
    [videoVC startAnimationWithType:KZVideoViewShowTypeSingle];
            
    
}
#pragma mark - KZVideoViewControllerDelegate
- (void)videoViewController:(KZVideoViewController *)videoController didRecordVideo:(KZVideoModel *)videoModel {
    _videoModel = videoModel;
    
    NSError *error = nil;
    NSFileManager *fm = [NSFileManager defaultManager];
    NSDictionary *attri = [fm attributesOfItemAtPath:_videoModel.videoAbsolutePath error:&error];
    if (error) {
        NSLog(@"error:%@",error);
    }
    
    NSURL *videoUrl = [NSURL fileURLWithPath:_videoModel.videoAbsolutePath];
    
    UIImage *img  =  [self cutMovieImageWith:videoUrl];
    _videoPath =[videoUrl absoluteString];
    NSDictionary *dict=[NSDictionary dictionaryWithObjectsAndKeys:@2,@"type",img,@"img", nil];
    [_dataAr insertObject:dict atIndex:[_dataAr count]];
    [_videoNumAr addObject:dict];
    [self showData:_dataAr];
    
    _videoPath =_videoModel.videoAbsolutePath;
    
}

- (void)videoViewControllerDidCancel:(KZVideoViewController *)videoController {
    NSLog(@"没有录到视频");
}


#pragma mark 获取视频首帧图片
-(UIImage*)cutMovieImageWith:(NSURL*)urlString{
    //创建URL
    NSURL *url=urlString;
    //根据url创建AVURLAsset
    AVURLAsset *urlAsset=[AVURLAsset assetWithURL:url];
    //根据AVURLAsset创建AVAssetImageGenerator
    AVAssetImageGenerator *imageGenerator=[AVAssetImageGenerator assetImageGeneratorWithAsset:urlAsset];
    imageGenerator.appliesPreferredTrackTransform = YES;
    /*截图
     * requestTime:缩略图创建时间
     * actualTime:缩略图实际生成的时间
     */
    NSError *error=nil;
    CMTime time=CMTimeMakeWithSeconds(1, 1);//CMTime是表示电影时间信息的结构体，第一个参数表示是视频第几秒，第二个参数表示每秒帧数.(如果要活的某一秒的第几帧可以使用CMTimeMake方法)
    CMTime actualTime;
    CGImageRef cgImage= [imageGenerator copyCGImageAtTime:time actualTime:&actualTime error:&error];
    if(error){
        //        DSLog(@"截取视频缩略图时发生错误，错误信息：%@",error.localizedDescription);
        return nil;
    }
    CMTimeShow(actualTime);
    UIImage *cutImage=[UIImage imageWithCGImage:cgImage];//转化为UIImage
    return cutImage;
}

@end
